import { parseKeyCode } from '../helpers/key-code-map';
import { HandlerEvent } from '../helpers/event-handler';
import { KeyboardPool } from '../helpers/keyboard-pool';
import { TRegisterKeyboardMap } from '../types/core.type';
/**
 * 键盘核心Core
 */
class KeyboardCore {
	constructor() {
		this.init();
	}

	private KeyJoinSymbol = '+';

	private readonly eventHandle: HandlerEvent = new HandlerEvent();

	// 注册的键盘池
	private readonly keyboardPool: KeyboardPool = new KeyboardPool();

	/**
	 * 初始化
	 */
	init() {
		this.eventHandle.setHandlerCallback(this.onKeyDownEventHandle.bind(this));
		this.eventHandle.bindKeyboardEvent(); // 绑定事件
	}

	/**
	 * 注册事件
	 * @param keyboardMap
	 */
	public registerCode(keyboardMap: TRegisterKeyboardMap) {
		for (const key in keyboardMap) {
			this.keyboardPool.setKeyboard(key, keyboardMap[key]);
		}
	}

	/**
	 * 序列化键盘字符
	 * @param event
	 * @returns {string}
	 */
	private parseKeyboardString(event: any): string {
		let keyboardList = [];
		const { ctrlKey, altKey, shiftKey } = event;
		const keyName = parseKeyCode(event.keyCode); // 将事件code转为中文
		const sortList = [
			{
				key: 'CTRL',
				value: ctrlKey,
			},
			{
				key: 'SHIFT',
				value: shiftKey,
			},
			{
				key: 'ALT',
				value: altKey,
			},
		];

		if (ctrlKey || shiftKey || altKey) {
			sortList.forEach((sortItem, index) => {
				if (sortItem.value) {
					keyboardList[index] = sortItem.key;
				}
			});
		}

		// 添加当前的其他数字键
		if (keyName) {
			keyboardList.push(keyName);
		}

		// 清空空字符
		keyboardList = keyboardList.filter((itm) => itm);
		const keyboardStringList = keyboardList.join(this.KeyJoinSymbol);
		return keyboardStringList;
	}

	/**
	 * 键盘事件
	 * @param event
	 */
	onKeyDownEventHandle(event: any) {
		const keyCodeString = this.parseKeyboardString(event);
		console.log('key event：', keyCodeString);
		const keyboardHandle = this.keyboardPool.getKeyboard(keyCodeString);
		if (keyboardHandle) {
			if (this.keyboardPool.hasLock(keyCodeString)) {
				console.log('锁住了！');
				return;
			}
			keyboardHandle(event);
		}
	}
}

export { KeyboardCore };
